$("body").show();
var vm = {
	templateType: 1, //数据源1-原始记录，2-检验报告
	testItemId: '',//检测项id
	data: [], //数据源,
	timeout: null,//模糊查询时间控件
	searchObj:{},//模糊查询对象
	searchNowTab: '',//当前正在进行的模糊查询
	pagination: null,
	init: function(templateType, testItemId, boo) {
		this.templateType = templateType;
		this.testItemId = testItemId;
		this.loadCss(boo);
		this.initName();
		this.initSearch();
		this.initScroll();
		this.loadSource();

		var $this = this;
		$(window).resize(function() {
			$this.loadCss(boo);
		});
		$("#report .reload").click(function(){
			$this.loadSource();
		})
	},
	loadCss: function(boo) {
		var height = $(window).height() - 20;
		if(boo) height += 20;
		$("#app").height(height);

		var portlet_height = height - 17;
		if(boo) portlet_height += 17;
		$("#app>.portlet").height(portlet_height);

		var form_height = portlet_height - $("#app>.portlet>.portlet-title").height();
		if(boo) form_height = portlet_height;
		$("#app>.portlet>.portlet-body").height(form_height);
		$("#form>.form-body").height(form_height - 15);
		if(boo) $("#form>.form-body").height(form_height);

		$("#form>.form-body>.row>.col-md-10").width($("#form>.form-body>.row").width() - 332);
	},
	//标签页滚动条样式
	initScroll: function(){
		$("#tabs-title").after('<div id="scrollbar-div"><div class="scrollbar"></div></div>');
		var time1 = null,time2 = null;
		this.addEvent($("#tabs-title"),$("#scrollbar-div"),time1,time2);
		this.addEvent($("#scrollbar-div"),$("#tabs-title"),time2,time1);
	},
	addEvent: function(target1,target2,timer1,timer2){
		var $this = this;
		target1.scroll(function () {
			if(timer1 != null) clearTimeout(timer1);
		    // 解除滚动监听事件，否则两个滚动条一起监听，会导致互相影响
		    target2.unbind("scroll mousewheel touchmove");
		    // 禁止另外一个滚动条滚动，只有在下面定时器绑定事件后才允许滚动
		    target2.on('scroll mousewheel touchmove', function (e) {
		        e.preventDefault();
		        e.stopPropagation();
		        return false;
		    });
		    target2.scrollLeft(target1.scrollLeft());
		    timer1 = setTimeout(function () {
		        target2.unbind('scroll mousewheel touchmove');
		        $this.addEvent(target2,target1,timer2,timer1);
		    }, 500);
		});
	},
	//初始化模板名称相关
	initName: function() {
		if (!$("#nameDiv input").val()) $("#nameDiv .placeholder").show();
		$("#nameDiv .placeholder").click(function() {
			$("#nameDiv input").focus();
		});
		$("#nameDiv input").focus(function() {
			$("#nameDiv .placeholder").hide();
		}).blur(function() {
			if (!$(this).val()) $("#nameDiv .placeholder").show();
		});
	},
	//初始化模糊查询相关
	initSearch: function() {
		$("#placeholder").click(function() {
			$("#searchInput").focus();
		});
		$("#searchInput").focus(function() {
			$("#placeholder").hide();
		}).blur(function() {
			if (!$(this).val()) $("#placeholder").show();
		});
		var $this = this;
		if (this.IEVersion() < 9) {
			$("#searchInput").bind('input propertychange', function() {
				if(!$this.searchNowTab) return;
				$this.searchObj[$this.searchNowTab].filter = $(this).val();
				if($this.timeout != null) clearTimeout($this.timeout);
				$this.timeout = setTimeout(function(){
					for (var i = 0; i < $this.data.length; i++) {
						if ($this.data[i].groupName === $this.searchNowTab) {
							$this.loadSourceContent($this.data[i].list, $this.data[i].dataType,$this.searchNowTab);
							break;
						}
					}
				},500);
			});
		} else {
			$("#searchInput").on('input', function() {
				if(!$this.searchNowTab) return;
				$this.searchObj[$this.searchNowTab].filter = $(this).val();
				if($this.timeout != null) clearTimeout($this.timeout);
				$this.timeout = setTimeout(function(){
					for (var i = 0; i < $this.data.length; i++) {
						if ($this.data[i].groupName === $this.searchNowTab) {
							$this.loadSourceContent($this.data[i].list, $this.data[i].dataType,$this.searchNowTab);
							break;
						}
					}
				},500);
			});
		}
	},
	//加载数据源数据
	loadSource: function() {
		var $this = this;
		var url = '/sdm/dataSource/query?testItemId=' + this.testItemId + '&templateType=' + this.templateType;
		App.get(url, function(result) {
			if (result && result.success) {
				if (result.obj && result.obj.length > 0) {
					$this.data = result.obj;
					$this.loadSourceTab();
				} else {
					$this.data = [];
				}
			}
		}, function(msg) {
			console.log(msg);
			alert(msg);
		});
	},
	//加载数据源标签
	loadSourceTab: function() {
		var htmlStr = '<div style="white-space:nowrap;overflow: hidden;box-sizing: content-box;">';
		for (var i = 0; i < this.data.length; i++) {
			htmlStr += '<div class="tab-title" onclick="vm.tabClick(this,\'' + this.data[i].groupName + '\')">' + this.data[i]
				.groupName + '</div>';
		}
		htmlStr += '</div>';
		$("#tabs-title").html(htmlStr);

		var tab_list = $("#tabs-title .tab-title"),
			width = 0,index = 0;
		for (var i = 0; i < tab_list.length; i++) {
			if ($(tab_list[i]).text() == this.searchNowTab) {
				index = i;
			}
			width += $(tab_list[i]).width();
		}
		$(tab_list[index]).click();
		width += (tab_list.length - 1) * 10;
		width += 10;
		$("#tabs-title").off("mousewheel");
		if (width > $("#tabs-title").width()) {
			$("#tabs-title>div").width(width);
			$("#scrollbar-div").height(11);
		} else {
			$("#scrollbar-div").height(0);
		}
		$("#scrollbar-div .scrollbar").width(width);
	},
	//标签的点击事件
	tabClick: function(e, tab) {
		this.searchNowTab = tab;
		$("#tabs-title .tab-title.cas").removeClass("cas");
		$(e).addClass("cas");
		// if(tab == '样品参数') {
		// 	$("#addSample").show();
		// 	$("#tabs-content").addClass("isSample");
		// } else {
		// 	$("#addSample").hide();
		// 	$("#tabs-content").removeClass("isSample");
		// }
		for (var i = 0; i < this.data.length; i++) {
			if (this.data[i].groupName === tab) {
				this.initPagination(this.data[i].dataType,tab,this.data[i].list);
				this.loadSourceContent(this.data[i].list, this.data[i].dataType,tab);
				break;
			}
		}
	},
	//初始化分页控件
	initPagination: function(dataType,tab,data){
		if(!this.searchObj[tab]) {
			if(dataType == 2){
				this.searchObj[tab] = {
					filter: '',
					pageCurrent: 1,
					pageSize: 15,
					total: data.length,
				}
			} else {
				this.searchObj[tab] = {
					filter: '',
				}
			}
		}
		if(dataType == 2){
			$("#pagebar").show();
			$("#tabs-content").addClass("hasPagination");
			if(this.pagination == null){
				var $this = this;
				$("#pagebar").jqpagination({
					automatic: true,
					total: this.searchObj[tab].total,
					pageSize: this.searchObj[tab].pageSize,
					onChange: function(page){
						$this.searchObj[tab].pageCurrent = page;
						$this.loadSourceContent(data, dataType,tab);
					}
				});
			} else {
				$("#pagebar").jqpagination("setOptions",this.searchObj[tab]);
			}
		} else {
			$("#pagebar").hide();
			$("#tabs-content").removeClass("hasPagination");
		}
	},
	//加载内容
	loadSourceContent: function(data, dataType,tab) {
		var htmlStr = '',
			searchData = this.searchObj[tab],
			start = dataType == 2 ? (searchData.pageCurrent - 1) * searchData.pageSize : 0;
		for (var i = start; i < data.length; i++) {
			if(!data[i].name){
				continue;
			}
			if (dataType == 2) {
				if(searchData.filter && data[i].name.indexOf(searchData.filter) == -1) continue;
				if(start >= start + searchData.pageSize) break;
				htmlStr += '<div class="item" onclick="vm.itemClick(this)" placeHolder="' + escape(data[i].placeHolder) +
					'" title="' + data[i].name + '">';
				htmlStr += '<div class="index">' + (i + 1) + '</div>';
				htmlStr += '<div class="text">' + data[i].name + '</div>';
				htmlStr += '</div>';
			} else {
				if (data[i].children && data[i].children.length > 0) {
					var boo = searchData.filter && data[i].name.indexOf(searchData.filter) == -1;
					var chtml = loadChild(data[i].children, 43, 21, boo);
					if(chtml) {
						htmlStr += '<div>';
						htmlStr +=
							'<div class="treeItem opened" onclick="vm.showOrHideNode(this)" style="padding-left: 43px;background-position: 21px center;" title="' +
							data[i].name + '">' + data[i].name + '</div>';
						htmlStr += chtml;
						htmlStr += '</div>';
					}
				} else {
					if(searchData.filter && data[i].name.indexOf(searchData.filter) == -1) continue;
					htmlStr += '<div class="treeItem" onclick="vm.itemClick(this)" placeHolder="' + escape(data[i].placeHolder) +
						'" style="padding-left: 43px;" title="' + data[i].name + '">' + data[i].name + '</div>';
				}
			}
		}

		$("#tabs-content").html(htmlStr);

		//树形子节点添加
		function loadChild(childData, left, imgLeft,boo) {
			var chtmlStr = '';
			for (var i = 0; i < childData.length; i++) {
				if(!childData[i].name){
					continue;
				}
				if (childData[i].children && childData[i].children.length > 0) {
					var boo2 = searchData.filter && childData[i].name.indexOf(searchData.filter) == -1;
					var chtml = loadChild(childData[i].children, left + 30, imgLeft + 19, boo2);
					if(chtml){
						chtmlStr += '<div class="treeItem opened" onclick="vm.showOrHideNode(this)" style="padding-left: ' + (left + 30) +
							'px;background-position: ' + (imgLeft + 19) + 'px center;" title="' + childData[i].name + '">' + childData[i].name + '</div>' + chtml;
					} 
					
				} else {
					if(boo && searchData.filter && childData[i].name.indexOf(searchData.filter) == -1) continue;
					chtmlStr += '<div class="treeItem" onclick="vm.itemClick(this)" placeHolder="' + escape(childData[i].placeHolder) +
						'" style="padding-left: ' + (left + 30) + 'px;" title="' + childData[i].name + '">' + childData[i].name + '</div>';
				}
			}
			if(chtmlStr) chtmlStr = '<div>' + chtmlStr + '</div>';
			return chtmlStr;
		}
	},
	//展示或隐藏子节点
	showOrHideNode: function(e) {
		if ($(e).hasClass("opened")) {
			$(e).removeClass("opened");
			$(e).addClass("closed");
			$(e).next().hide();
		} else {
			$(e).removeClass("closed");
			$(e).addClass("opened");
			$(e).next().show();
		}
	},
	//点击选项加载值到文档中
	itemClick: function(e) {
		var placeHolder = unescape($(e).attr("placeHolder"));
		var obj = document.getElementById("pageOfficeCtrl").Document;
		obj.Application.Selection.Text = placeHolder;
	},
	IEVersion: function() {
		var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
		var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
		var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
		var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
		if (isIE) {
			var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
			reIE.test(userAgent);
			var fIEVersion = parseFloat(RegExp["$1"]);
			if (fIEVersion == 7) {
				return 7;
			} else if (fIEVersion == 8) {
				return 8;
			} else if (fIEVersion == 9) {
				return 9;
			} else if (fIEVersion == 10) {
				return 10;
			} else {
				return 6; //IE版本<=7
			}
		} else if (isEdge) {
			return 'edge'; //edge
		} else if (isIE11) {
			return 11; //IE11
		} else {
			return 9999; //不是ie浏览器
		}
	},
};
